<template>
    <div class="search">
        <div class="search-content">
            <div class="search-margin"></div>

            <div class="custom-tag">
                <div class="custom-content">
                    <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-device-tablet-search"
                        width="28" height="28" viewBox="0 0 24 24" stroke-width="1.5" stroke="#865E2A" fill="none"
                        stroke-linecap="round" stroke-linejoin="round">
                        <path stroke="none" d="M0 0h24v24H0z" fill="none" />
                        <path d="M11.5 21h-5.5a1 1 0 0 1 -1 -1v-16a1 1 0 0 1 1 -1h12a1 1 0 0 1 1 1v7" />
                        <path d="M18 18m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0" />
                        <path d="M20.2 20.2l1.8 1.8" />
                    </svg>
                    <span class="custom-text">搜索题目</span>
                </div>
            </div>

            <!-- 表格 -->
            <div class="search-table">
                <div class="search-button global-button">
                    <el-button @click="resetConditionFilter">清除状态过滤器</el-button>
                    <el-button @click="resetDifficultyFilter">清除难度过滤器</el-button>
                    <el-button @click="resetTagFilter">清除标签过滤器</el-button>
                    <el-button @click="clearFilter">清除所有过滤器</el-button>
                </div>
                <el-table ref="filterTable" stripe :data="tableData.slice((currpage - 1) * pagesize, currpage * pagesize)"
                    style="width: 100%">

                    <!-- <el-table-column prop="condition" label="状态" sortable width="100" column-key="condition"
              :filters="[{ text: '未做', value: 1 }, { text: '错题', value: 2 }, { text: '已做', value: 3 }]"
              :filter-method="filterCondition">>
              <template slot-scope="scope"> -->
                    <!-- 1: 未做；2：错题：3：已做 -->
                    <!-- {{ scope.row.condition === 1 ? '未做' : scope.row.condition === 2 ? '错题' : scope.row.condition === 3 ? '已做'
                  : '' }} -->
                    <!-- <svg v-if="scope.row.condition === 1" xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-clipboard" width="28"
                  height="28" viewBox="0 0 24 24" stroke-width="2" stroke="#ff9000" fill="none" stroke-linecap="round"
                  stroke-linejoin="round">
                  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
                  <path d="M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2" />
                  <path d="M9 3m0 2a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v0a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2z" />
                </svg>
  
                <svg v-if="scope.row.condition === 2" xmlns="http://www.w3.org/2000/svg"
                  class="icon icon-tabler icon-tabler-clipboard-x" width="28" height="28" viewBox="0 0 24 24"
                  stroke-width="2" stroke="#ff9000" fill="none" stroke-linecap="round" stroke-linejoin="round">
                  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
                  <path d="M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2" />
                  <path d="M9 3m0 2a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v0a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2z" />
                  <path d="M10 12l4 4m0 -4l-4 4" />
                </svg>
  
                <svg v-if="scope.row.condition === 3" xmlns="http://www.w3.org/2000/svg"
                  class="icon icon-tabler icon-tabler-clipboard-check" width="28" height="28" viewBox="0 0 24 24"
                  stroke-width="2" stroke="#ff9000" fill="none" stroke-linecap="round" stroke-linejoin="round">
                  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
                  <path d="M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2" />
                  <path d="M9 3m0 2a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v0a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2z" />
                  <path d="M9 14l2 2l4 -4" />
                </svg>
              </template>
            </el-table-column> -->
                    <el-table-column prop="tableId" v-if="false">
                    </el-table-column>

                    <el-table-column prop="record" label="题目" width="550">
                        <template slot-scope="scope">
                            <el-link @click="dialogVisible = true; everyDialog((scope.row.tableId))">{{
                                scope.row.record }}</el-link>
                        </template>
                    </el-table-column>


                    <el-table-column prop="difficulty" label="难度" sortable :sort-method="sortMethod" style="width: 10%"
                        column-key="difficulty"
                        :filters="[{ text: '简单', value: '简单' }, { text: '中等', value: '中等' }, { text: '困难', value: '困难' }]"
                        :filter-method="filterDifficulty">
                    </el-table-column>

                    <el-table-column prop="tag" label="标签" sortable style="width: 20%" column-key="tag" :filters="[{ text: '数组', value: '数组' },
                    { text: '栈', value: '栈' },
                    { text: '堆', value: '堆' },
                    { text: '树', value: '树' },
                    { text: '二叉树', value: '二叉树' },
                    { text: '队列', value: '队列' },
                    { text: '链表', value: '链表' },]" :filter-method="filterTag" filter-placement="bottom-end">
                        <template slot-scope="scope">
                            <!-- <el-tag type="primary" disable-transitions>{{ scope.row.tag }}</el-tag> -->
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination">
                    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :current-page.sync="currpage" :page-sizes="[20, 50, 100]" :page-size="pagesize"
                        layout="sizes, prev, pager, next" :total="tableData.length">
                    </el-pagination>
                </div>
            </div>

        </div>
        <el-dialog :visible.sync="dialogVisible" width="30%">
            <span class="dialog-banner"><el-link class="elLinkBigger" @click="linkRecord">{{ dialogBanner
            }}</el-link></span>
            <div class="dialog-tag">
                <ul>
                    <li v-for="tag in tags" :key="tag">{{ tag }}</li>
                </ul>
            </div>
            <div class="dialog-info">{{ dialogInfo }}</div>
            <!-- 收藏、记录 button -->
            <el-button class="dialog-collection" :icon="Collection" circle @click="toggleCollection"></el-button>
            <el-button class="dialog-record" v-if="showRecordButton" :icon="Record" circle
                @click="toggleRecord"></el-button>

            <span slot="footer" class="dialog-footer">
            </span>
        </el-dialog>

    </div>
</template>
  
<script>
import { isRecord } from '@/utils/useful';
import { searchAnswers } from '@/api/search';
import { getProUid } from '@/utils/useful';
import { isCollection } from '@/utils/useful';
import { createRecord } from '@/api/record'
import { deleteCollection } from '@/api/collection'
import { createCollection } from '@/api/collection'
import { doneRecord } from '@/api/record'
import { getTime } from '@/utils/useful'



export default {
    data() {
        return {
            tableData: [],
            pagesize: 20,
            currpage: 1,
            dialogVisible: false,
            problemInfoArray: [],
            dialogBanner: '',
            tags: [],
            dialogInfo: '',
            Collection: "",
            Record: "",
            externalUrl: '',
            showRecordButton: false,
            searchWord: '',
        }
    },
    mounted() {
        Promise.all([
            searchAnswers("LC", this.$route.query.keyword, 2000),
            searchAnswers("OJ", this.$route.query.keyword, 2400),
        ])
            .then((results) => {
                const lcRes = results[0];
                const ojRes = results[1];
                const lcProblemInfoArray = Object.values(lcRes.data);
                const ojProblemInfoArray = Object.values(ojRes.data);
                const difficultyMapping = {
                    "Medium": "中等",
                    "Easy": "简单",
                    "Hard": "困难",
                    "very easy": "简单",
                    "little easy": "简单",
                    "regular": "中等",
                    "little hard": "困难",
                    "very hard": "困难",
                };

                // 处理 LC 记录
                for (let i = 0; i < lcProblemInfoArray.length; i++) {
                    const problemInfo = lcProblemInfoArray[i];
                    const d = difficultyMapping[problemInfo.difficulty] || '';

                    const tableEle = {
                        tableId: i,
                        difficulty: d,
                        record: problemInfo.source + ': ' + problemInfo.title,
                        tag: null
                    };
                    this.tableData.push(tableEle);
                }

                // 处理 OJ 记录
                for (let i = 0; i < ojProblemInfoArray.length; i++) {
                    const problemInfo = ojProblemInfoArray[i];
                    const d = difficultyMapping[problemInfo.difficulty] || '';

                    const tableEle = {
                        tableId: i + lcProblemInfoArray.length,
                        difficulty: d,
                        record: problemInfo.source + ': ' + problemInfo.title,
                        tag: null
                    };
                    this.tableData.push(tableEle);
                }

                this.problemInfoArray.push(...lcProblemInfoArray);
                this.problemInfoArray.push(...ojProblemInfoArray);

            })
            .catch((error) => {
                console.error(error);
            });
    },
    methods: {
        resetConditionFilter() {
            this.$refs.filterTable.clearFilter('condition');
        },
        resetDifficultyFilter() {
            this.$refs.filterTable.clearFilter('difficulty');
        },
        resetTagFilter() {
            this.$refs.filterTable.clearFilter('tag');
        },
        clearFilter() {
            this.$refs.filterTable.clearFilter();
        },
        formatter(row, column) {
            return row.address;
        },
        filterTag(value, row) {
            return row.tag === value;
        },
        filterDifficulty(value, row) {
            return row.difficulty === value;
        },
        sortMethod(a, b) {
            const difficultyOrder = {
                '简单': 0,
                '中等': 1,
                '困难': 2,
            };
            const difficultyA = difficultyOrder[a.difficulty];
            const difficultyB = difficultyOrder[b.difficulty];
            return difficultyA - difficultyB;
        },
        filterCondition(value, row) {
            return row.condition === value;
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pagesize = val;
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.currpage = val;
        },
        toggleCollection() {
            // console.log(this.problemUid)

            if (this.Collection === "el-icon-star-off") {
                this.Collection = "el-icon-star-on"
                createCollection(null, this.problemUid, "").then((res) => {
                    // console.log(res.data)
                });
            }
            else {
                this.Collection = "el-icon-star-off"
                deleteCollection(this.problemUid).then((res) => {
                    console.log(res.data)
                })
            }
        },
        toggleRecord() {
            if (this.Record === "el-icon-goods") {
                this.Record = 'el-icon-s-goods'
                doneRecord(this.problemUid, 0, getTime(), "done").then((res) => {
                    console.log(res.data)
                });
            }
            else { }
        },
        async everyDialog(tableId) {
            this.tags.length = 0

            this.dialogBanner = this.tableData[tableId].record;
            this.dialogInfo = this.problemInfoArray[tableId].description;
            this.externalUrl = this.problemInfoArray[tableId].url;
            this.id = this.problemInfoArray[tableId].id;
            this.source = this.problemInfoArray[tableId].source;
            this.tags.push(this.tableData[tableId].difficulty)
            //标签

            if (this.tags[0] === '') {
                this.tags.length = 0
            }
            this.problemUid = await getProUid(this.source, this.id);

            let c = isCollection(this.problemUid)

            c.then((value) => {
                if (value === true) {
                    this.Collection = "el-icon-star-on"
                }
                else {
                    this.Collection = "el-icon-star-off"
                }
            })

            let temp = this.problemUid;
            let t = isRecord(temp);
            // console.log(t)

            t.then((value) => {
                if (value === 1) {
                    this.showRecordButton = false;
                } else if (value === 2) {
                    this.showRecordButton = true;
                    this.Record = 'el-icon-s-goods';
                } else if (value === 3) {
                    this.showRecordButton = true;
                    this.Record = 'el-icon-goods';
                } else {
                    console.log("error: isRecord");
                }
            });
        },
        linkRecord() {
            createRecord(this.problemUid).then((res) => {
                window.location.href = this.externalUrl;
            })
        },

    }
}
</script>
  
<style lang="scss">
.search {
    background-color: #FFF7EF;

    .search-content {
        width: 1200px;
        margin: 0 auto;

        .search-margin {
            height: 20px;
        }
    }

    .custom-tag {
        background-color: transparent;
        display: block;
        padding: 6px 10px;
        border-radius: 20px;
        width: 130px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .25);
    }

    .custom-content {
        display: flex;
        align-items: center;
    }

    .custom-text {
        margin-left: 8px;
        font-size: 20px;
        font-weight: bold;
        color: #865E2A;
    }

    .deposit-button {
        margin-top: 20px;
    }

    svg {
        vertical-align: middle;
    }
}
</style>